package com.itheima.web.Request;



import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


/*
*  中文乱码问题的解决方案
* */
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.解决乱码 POST，getReader()
        request.setCharacterEncoding("UTF-8");//设置字符输入流的编码

        //2.获取username
        String username = request.getParameter("username");
        System.out.println(username);

        //3.GET，获取请求参数的方式：getQueryString
        // 乱码原因 tomcat默认解码字符集与浏览器的编码字符集不同

        // 使用字符集解决乱码问题
       /* //3.1 使用tomcat的解码字符集：ISO-8859-1 进行编码
        String encode = URLEncoder.encode(username, "ISO-8859-1");

        //3.2 再使用浏览器的编码字符集：utf-8 进行解码
        username = URLDecoder.decode(encode, "utf-8");
        System.out.println(username);*/

       // 使用数组解决乱码问题
      /* // 3.1 将乱码数据转为字节数组
        byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);

        //3.2 字节数组再解码
        username = new String(bytes,StandardCharsets.UTF_8);*/

      //简化版
        username = new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);

        System.out.println(username);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
